<script setup>
import {ref , onMounted} from 'vue'
import {findAllClazzApi} from '../../api/clazz'
import {queryStuApi ,addStuApi,queryStuByIdApi,updateStuApi,delStuByIdApi,violationStuApi} from '../../api/stu'
import { ElMessage,ElMessageBox } from 'element-plus'

// 搜索栏
const searchStu = ref({name:'',degree:'',clazz:''})

// 元数据
const gender = ([{name:'男',value:'1'},{name:'女',value:'2'}])
const degree = ([{name:"初中",value:"1"},{name:"高中",value:"2"},{name:"大专",value:"3"},
                 {name:"本科",value:"4"},{name:"硕士",value:"5"},{name:"博士",value:"6"}])
const isCollege = ([{name:'是',value:'1'},{name:'否',value:'0'}])

// 加载班级数据
const clazz = ref()

onMounted(() => {
  clazzList()
})

const clazzList = async () =>{
  const result = await findAllClazzApi()
  if(result.code){
      clazz.value = result.data
  }
}
onMounted(()=>{
  search()
})

// 查询按钮
const search = async () =>{
  const result = await queryStuApi(searchStu.value.name,searchStu.value.degree,searchStu.value.clazz,currentPage.value,pageSize.value)
  if(result.code){
    stuList.value = result.data.rows
    total.value = result.data.total
  }
}

// 清空按钮
const clear = () => {
  searchStu.value = {name:'',degree:'',clazz:''}
  search()
}

// 学员数据
const stuList = ref([])

// 分页条信息
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const background = true

// 分页查询
const handleSizeChange = () =>{
  search()
}
const handleCurrentChange = () =>{
  search()
}
// 新增学员
const addStu = ()=>{
  dialogVisible.value = true
  dialogTitle.value = '新增学员'
  student.value = {
    name:'',
    no:'',
    gender:'',
    phone:'',
    idCard:'',
    isCollege:'',
    address:'',
    degree:'',
    graduationDate:'',
    clazzId:''
  }
}

// 学员对象
const student = ref({
  name:'',
  no:'',
  gender:'',
  phone:'',
  idCard:'',
  isCollege:'',
  address:'',
  degree:'',
  graduationDate:'',
  clazzId:''
})


// dialog弹窗
const dialogVisible = ref(false)
const dialogTitle = ref('新增学员')

// 校验条件
// 数据输入时校验
const rules = ref({
  name: [
    { required: true, message: '姓名为必填项', trigger: 'blur' },
    { min: 2, max: 6, message: '姓名长度应在2到6个字之间', trigger: 'blur' }
  ],
  no:[
    { required: true, message: '学号为必填项', trigger: 'blur' },
    { pattern: /\d{10}$/g, message: '学号长度为10', trigger: 'blur' }
  ],
  gender:[
    { required: true, message: '性别为必填项', trigger: 'blur' },
  ],
  phone:[
    { required: true, message: '手机号为必填项', trigger: 'blur' },
    { pattern: /^1\d{10}$/g, message: '请输入有效的手机号', trigger: 'blur' }
  ],
  ///^\d{17}[\dXx]$/
  idCard:[
    {required: true, message: '身份证号为必填项', trigger: 'blur' },
    {pattern: /^\d{17}[\dXx]$/g , message: '请输入合法的身份证号', trigger: 'blur' }
  ],
  isCollege:[
    {required: true, message: '是否为院校学员为必填项', trigger: 'blur' },
  ]
});

// 数据提交时校验
const stuRef = ref()

// 保存数据
const save = async () =>{
  stuRef.value.validate(async (valid) =>{
    if(valid){ //校验通过
    let result
      if(student.value.id){
        result = await updateStuApi(student.value)
      }else{
        result = await addStuApi(student.value)
      }
      if(result.code){
        dialogVisible.value = false
        ElMessage.success('操作成功')
        search()
      }else{
        ElMessage.error(result.msg)
      }
    }else{ // 校验不通过
        ElMessage.error('校验不通过')
    }
  })
}

// 编辑数据
// 1.查询回显
const edit = async (id) => {
  const result = await queryStuByIdApi(id)
  if(result.code){
    dialogTitle.value = '编辑数据'
    dialogVisible.value = true
    student.value = result.data
    student.value.gender = student.value.gender.toString()
    student.value.isCollege = student.value.isCollege.toString()
    student.value.degree = student.value.degree.toString()
  }
}

// 删除数据
const del = async(id) =>{
  ElMessageBox.confirm('您确定要删除信息吗？','提示',
    {confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning'})
    .then(async () => {
      const result = await delStuByIdApi(id)
      if(result.code){
        ElMessage.success('删除成功')
        search()
      }else{
       ElMessage.error(result.msg)
      }
    }).catch(() => {
       ElMessage.info('您已取消删除')
    });
}

// 批量删除
const selectionIds = ref([])

const handleSelectionChange = (selection) =>{
  selectionIds.value = selection.map(item => item.id)
}

const delIds = () =>{
  ElMessageBox.confirm('您确定要删除信息吗？','提示',
    {confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning'})
    .then(async () => {
    if(selectionIds.value && selectionIds.value.length > 0){
      const result = await delStuByIdApi(selectionIds.value)
      if(result.code){
        ElMessage.success('删除成功')
        search()
      }else{
       ElMessage.error(result.msg)
      }
    }else{
      ElMessage.info('您没有选取任何内容')
    }}).catch(() => {
       ElMessage.info('您已取消删除')
    });
}

// 违纪处理

const dialogVisibleVio = ref(false)
const dialogTitleVio = ref('提示')
const violations = ref({score:''})
// 违纪处理
const violation = async (id) =>{
  dialogVisibleVio.value = true
  dialogTitleVio.value = '违纪处理'
  violations.value.score=''
  student.value.id = id
  if(vioRef.value){
    vioRef.value.resetFields()
  }
}
const save_vio = async () =>{
    const result = await violationStuApi( student.value.id , violations.value.score)
    if(result.code){
      dialogVisibleVio.value = false
      ElMessage.success('操作成功')
      search()
    }else{
      ElMessage.error(result.msg)
    }
  
}
const vioRef = ref()
const rules_vio = ref({
  violation:[
    {required: true, message: '这是必填项', trigger: 'blur' }
  ]
})



</script>

<template>
  
  <h1>学员管理</h1>
  <!-- 搜索栏 -->
   <div class="style">
  <el-form :inline="true" :model="searchStu" class="demo-form-inline">

    <el-form-item label="姓名">
      <el-input v-model="searchStu.name" placeholder="请输入学生姓名"  />
    </el-form-item>

    <el-form-item label="最高学历">
      <el-select
        v-model="searchStu.degree"
        placeholder="请选择"
      >
        <el-option v-for="d in degree" :key="d.value" :label="d.name" :value="d.value" />
      </el-select>
    </el-form-item>
    <el-form-item label="所属班级">
      <el-select
        v-model="searchStu.clazz"
        placeholder="请选择"
      >
        <el-option v-for="c in clazz" :key="c.id" :label="c.name" :value="c.id" />
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="search">查询</el-button>
      <el-button type="info" @click="clear">清空</el-button>
    </el-form-item>
  </el-form>
</div>

    <!-- 功能按钮  -->
  <div class="style">
    <el-button type="success" @click="addStu">+ 新增学员</el-button>
    <el-button type="danger" @click="delIds">- 批量删除</el-button>
  </div>

  <!-- 表格 -->
  <div class="style">
    <el-table :data="stuList" border style="width: 100%" @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="50"  align="center" @selection-change="handleSelectionChange" />
    <el-table-column prop="name" label="姓名" width="80" align="center"/>
    <el-table-column prop="no" label="学号" width="120" align="center"/>
    <el-table-column prop="clazzName" label="班级" width="120" align="center"/>
    <el-table-column prop="gender" label="性别" width="80" align="center">
      <template #default="scope">
      {{ scope.row.gender == 1 ?  '男':'女' }}
      </template>
    </el-table-column>
    <el-table-column prop="phone" label="手机号" width="120" align="center"/>
    <el-table-column prop="degree" label="最高学历" width="85" align="center">
      <template #default="scope">
        <span v-if="scope.row.degree == 1 ">初中</span>
        <span v-else-if="scope.row.degree == 2">高中</span>
        <span v-else-if="scope.row.degree == 3">大专</span>
        <span v-else-if="scope.row.degree == 4">本科</span>
        <span v-else-if="scope.row.degree == 5">硕士</span>
        <span v-else-if="scope.row.degree == 6">博士</span>
      </template>
    </el-table-column>
    <el-table-column prop="violationCount" label="违纪次数" width="85"align="center"/>
    <el-table-column prop="violationScore" label="违纪扣分" width="85"align="center"/>
    <el-table-column prop="updateTime" label="最后修改时间" width="180"align="center"/>
    <el-table-column  label="操作" align="center">
      <template #default="scope">
        <el-button type="primary" @click="edit(scope.row.id)">编辑</el-button>
        <el-button type="warning" @click="violation(scope.row.id)">违纪</el-button>
        <el-button type="danger" @click="del(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  </div>
  
  <!-- 分页条 -->
  <div class="style">
    <el-pagination
      v-model:current-page="currentPage"  
      v-model:page-size="pageSize"
      :page-sizes="[5,10, 20, 50, 100]"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>

   <!-- 新增/修改员工的对话框 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle">
      <el-form  :rules="rules" :model="student" ref="stuRef"  label-width="80px">
        <!-- 基本信息 -->
        <!-- 第一行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="student.name" placeholder="请输入学员姓名"></el-input>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="学号" prop="no">
              <el-input v-model="student.no" placeholder="请输入学员学号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="student.gender" placeholder="请选择性别" style="width: 100%;">
                <el-option v-for=" g in gender" :key="g.value" :label="g.name" :value="g.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="student.phone" placeholder="请输入手机号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idCard">
              <el-input v-model="student.idCard" placeholder="请输入身份证号码"></el-input>

            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否院校" prop="isCollege">
              <el-select v-model="student.isCollege" placeholder="请选择" style="width: 100%;">
                <el-option v-for=" i in isCollege" :key="i.value" :label="i.name" :value="i.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第四行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系地址">
              <el-input v-model="student.address" placeholder="请输入联系地址"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最高学历">
              <el-select v-model="student.degree" placeholder="请选择" style="width: 100%;">
                <el-option v-for="d in degree" :key="d.value" :label="d.name" :value="d.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第五行 -->
         <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="毕业时间">
              <el-date-picker v-model="student.graduationDate" type="date" style="width: 100%;" placeholder="选择日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属班级">
              <el-select v-model="student.clazzId" placeholder="请选择" style="width: 100%;">
                <el-option v-for="c in clazz" :key="c.id" :label="c.name" :value="c.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      
        <!-- 底部按钮 -->
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="save">保存</el-button>
          </span>
        </template>

    </el-dialog>

    <!-- 违纪处理对话框 -->
  <el-dialog v-model="dialogVisibleVio" :title="dialogTitleVio" width="500">
    <el-form :model="violations" :rules="rules_vio" ref="vioRef">
      <p>请输入违纪扣分</p>
      <el-form-item  prop="violation" >
        <el-input v-model="violations.score"/>
        </el-form-item>
    </el-form> 
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisibleVio = false">取消</el-button>
        <el-button type="primary" @click="save_vio">确定</el-button>
      </div>
    </template>
  </el-dialog>


</template>

<style scoped>
.style{
  margin: 15px ;
}
p{
  margin-bottom: 15px;
}
</style>